package com.sky.service.adminImpl;


import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.StatusConstant;
import com.sky.dto.CategoryDTO;
import com.sky.dto.CategoryPageQueryDTO;
import com.sky.entity.Category;
import com.sky.exception.IsExistException;
import com.sky.mapper.CategoryMapper;
import com.sky.result.PageResult;
import com.sky.service.CategoryService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

import static com.sky.constant.MessageConstant.CATEGORY_EXIST;
import static com.sky.constant.StatusConstant.ENABLE;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public void add(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO, category);
        Category name=categoryMapper.getByName(category.getName());
        if (name!=null){
            throw new IsExistException(CATEGORY_EXIST);
        }
        category.setStatus(ENABLE);
        categoryMapper.insert(category);
    }

    @Override
    public PageResult<Category> page(CategoryPageQueryDTO categoryPageQueryDTO) {
        PageResult<Category> result = new PageResult<>();
        PageHelper.startPage(categoryPageQueryDTO.getPage(),categoryPageQueryDTO.getPageSize());
        Page<Category> categories=(Page<Category>)categoryMapper.selectPage(categoryPageQueryDTO);
        result.setTotal(categories.getTotal());
        result.setRecords(categories.getResult());
        return result;
    }

    @Override
    public void startOrStop(Integer status, Long id) {
        Category category=Category.builder()
                .status(status)
                .id(id)
                .build();
        categoryMapper.update(category);
    }

    @Override
    public void edit(CategoryDTO categoryDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryDTO,category);
        categoryMapper.update(category);
    }

    @Override
    public void remove(Long id) {
        categoryMapper.delete(id);
    }

    @Override
    public List<Category> get(Integer type) {
        Category category=Category.builder()
                .status(ENABLE)
                .type(type)
                .build();
        return categoryMapper.selectType(category);
    }
}
